/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: TradeApi.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.trade;

import android.text.TextUtils;

import java.util.List;

import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.TradeDataManager;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.sdk.trade.bean.AssetListSocketResponse;
import io.bhex.sdk.trade.bean.CreateOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.trade.bean.OrderDealDetailResponse;
import io.bhex.sdk.Urls;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.network.BParamsBuilder;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.params.PostParams;
import io.bhex.baselib.network.response.ResultResponse;

public class TradeApi {

    /**
     * SubBalanceData  should not Unsub
     * @param observer
     */
    public static void SubBalanceData(final NetWorkObserver<List<AssetListResponse.BalanceBean>> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().RequestBalance(new NetWorkObserver<AssetListSocketResponse>(){

            @Override
            public void onShowUI(AssetListSocketResponse response) {
                if(response != null && response.data != null){
                    if(observer != null)
                        observer.onShowUI(response.data);
                }
            }

            @Override
            public void onError(String response) {
                if(observer != null)
                    observer.onError(response);

            }
        },new NetWorkObserver<AssetListResponse>(){

            @Override
            public void onShowUI(AssetListResponse response) {
                if(response != null && response.getBalance() != null){
                    if(observer != null)
                        observer.onShowUI(response.getBalance());
                }
            }

            @Override
            public void onError(String response) {
                if(observer != null)
                    observer.onError(response);
            }
        });
    }

    /**
     * RequestBalanceData
     * @param observer
     */
    public static void RequestBalanceData(SimpleResponseListener<AssetListResponse> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().getRequestCurrentBalance( observer);

        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ACCOUNT_GET_LIST)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
//                .addParam(Fields.FIELD_SYMBOL, )

//                .addParam(Fields.FIELD_ORDER_ID_PAGE,)
//                .addParam(Fields.FIELD_START_TIME,)
//                .addParam(Fields.FIELD_END_TIME,)
                .build();
        HttpUtils.getInstance().request(params, AssetListResponse.class, observer);
    }

    /**
     * RequestTokenBalance  should not Unsub
     * @param token
     * @param observer
     */
    public static void SubTokenBalanceChange(String token, SimpleResponseListener<AssetListResponse.BalanceBean> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().RequestTokenBalance(token, observer);
    }

    /**
     * SubSymbolOrder  should not Unsub
     * @param symbol
     * @param observer
     */
    public static void SubSymbolOrderChange(String symbol, SimpleResponseListener<OpenOrderResponse> observer){

        TradeDataManager.GetInstance().RequestSymbolOrder(symbol, observer);
    }

    /**
     * RequestOrder  should not Unsub
     * @param observer
     */
    public static void SubOrderChange( SimpleResponseListener<OpenOrderResponse> observer){

        TradeDataManager.GetInstance().RequestOrder(observer);
    }

    /**
     * RequestOpenOrder
     * @param observer
     */

    public static void RequestOpenOrder( SimpleResponseListener<OpenOrderResponse> observer){

        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ORDER_OPEN_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
//                .addParam(Fields.FIELD_START_TIME,)
//                .addParam(Fields.FIELD_END_TIME,)
                .addParam(Fields.FIELD_LIMIT,50)
                .build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);
    }

    /**
     * RequestSymbolOpenOrder
     * @param symbol
     * @param observer
     */
    public static void RequestSymbolOpenOrder(String symbol, SimpleResponseListener<OpenOrderResponse> observer){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ORDER_OPEN_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_SYMBOL_ID, symbol)
//                .addParam(Fields.FIELD_ORDER_ID_PAGE_FROM,)
//                .addParam(Fields.FIELD_START_TIME,)
                .addParam(Fields.FIELD_LIMIT,50)
                .build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);
    }

    /**
     * RequestFilterOpenOrder
     * @param data
     * @param observer
     */
    public static void RequestFilterOpenOrder(OpenOrderRequest data, SimpleResponseListener<OpenOrderResponse> observer){
        if(data == null)
            return;
        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_ORDER_OPEN_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam("base_token_id",data.baseToken.toUpperCase())
                .addParam("quote_token_id",data.quoteToken.toUpperCase())
                .addParam("side",data.orderStatus.toLowerCase())
                .addParam("type",data.priceMode.toLowerCase())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(data.orderPageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, data.orderPageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);
    }

    /**
     * RequestCancelAllOrder
     * @param listener
     */
    public static void RequestCancelAllOrder(String symbols, SimpleResponseListener<ResultResponse> listener){
        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_ORDER_CANCEL_BATCH)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .build();
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_ids",symbols.toUpperCase());
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, ResultResponse.class, listener);
    }

    /**
     * RequestCancelOrder
     * @param orderId
     * @param listener
     */
    public static void RequestCancelOrder(String orderId, SimpleResponseListener<OrderBean> listener){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ORDER_CANCEL)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_CLIENT_ORDER_ID, System.currentTimeMillis() + "")
                .addParam(Fields.FIELD_ORDER_ID, orderId)
                .build();
        HttpUtils.getInstance().request(params, OrderBean.class, listener);
    }



    /**
     * RequestCreateOrder
     * @param requestData
     * @param listener
     */
    public static void RequestCreateOrder(CreateOrderRequest requestData, SimpleResponseListener<OrderBean> listener) {
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ORDER_CREATE)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_EXCHANGE_ID2, requestData.exchangeId)
                .addParam(Fields.FIELD_SYMBOL_ID, requestData.symbol)
                .addParam(Fields.FIELD_SIDE, requestData.isBuyMode ? "buy" : "sell")
                .addParam(Fields.FIELD_TYPE, requestData.isLimitedPrice ? "limit" : "market")
                .addParam(Fields.FIELD_CLIENT_ORDER_ID, System.currentTimeMillis() + "")
                .addParam(Fields.FIELD_PRICE, requestData.price)
                .addParam(Fields.FIELD_QUANTITY, requestData.amount)
                .build();
        HttpUtils.getInstance().request(params, OrderBean.class, listener);
    }

    /**
     * RequestOrderMatchInfo
     * @param orderId
     * @param orderPageId
     * @param observer
     */
    public static void RequestOrderMatchInfo(String orderId, String orderPageId, SimpleResponseListener<OrderDealDetailResponse> observer){
        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_ORDER_MATCH_INFO)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_ORDER_ID, orderId)
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(orderPageId))
            builder.addParam(Fields.FIELD_TRADE_ID_PAGE, orderPageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OrderDealDetailResponse.class, observer);
    }

    /**
     * 获取历史委托
     *
     */
    public static void RequestHistoryEntrustOrders(OpenOrderRequest data, SimpleResponseListener<OpenOrderResponse> observer) {
        if(data == null)
            return;

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_ORDER_TRADE_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam("base_token_id",data.baseToken.toUpperCase())
                .addParam("quote_token_id",data.quoteToken.toUpperCase())
                .addParam("side",data.orderStatus.toLowerCase())
                .addParam("type",data.priceMode.toLowerCase())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(data.orderPageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, data.orderPageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);

    }

    public static void RequestSymbolHistoryEntrustOrders(String symbols, String pageId, SimpleResponseListener<OpenOrderResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_ORDER_TRADE_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_id",symbols.toUpperCase());
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);

    }
}
